import Avatar from '@material-ui/core/Avatar';
import { blue } from '@material-ui/core/colors';
import Dialog from '@material-ui/core/Dialog';
import DialogTitle from '@material-ui/core/DialogTitle';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemAvatar from '@material-ui/core/ListItemAvatar';
import ListItemText from '@material-ui/core/ListItemText';
import { makeStyles } from '@material-ui/core/styles';
import { Folder } from '@material-ui/icons';
import React, { useEffect } from 'react';
import { useRootFolders } from '../context';
import { queryRootFolders } from '../services';

const useStyles = makeStyles({
  avatar: {
    backgroundColor: blue[100],
    color: blue[600],
  },
});

export interface RootFolderDialogProps {
  open: boolean;
  onClose: (value?: string) => void;
}

export default function RootFolderDialog (props: RootFolderDialogProps) {
  const classes = useStyles();
  const { onClose, open } = props;
  const { rootFolders, setRootFolders } = useRootFolders();

  useEffect(() => {
    queryRootFolders()
      .then(res => {
        if (res.data) {
          setRootFolders(res.data);
        }
      });
  }, []);

  const handleClose = () => {
    onClose();
  };

  const handleListItemClick = (value: string) => {
    onClose(value);
  };

  return (
    <Dialog onClose={handleClose} aria-labelledby="simple-dialog-title" open={open}>
      <DialogTitle id="simple-dialog-title">设置根目录</DialogTitle>
      <List>
        {rootFolders.map((value) => (
          <ListItem button onClick={() => handleListItemClick(value)} key={value}>
            <ListItemAvatar>
              <Avatar className={classes.avatar}>
                <Folder/>
              </Avatar>
            </ListItemAvatar>
            <ListItemText primary={value}/>
          </ListItem>
        ))}
      </List>
    </Dialog>
  );
}
